package com.example.zxlwork;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;

import com.example.zxlwork.adapter.PageAdapter;
import com.example.zxlwork.fragmet.MineFragment;
import com.example.zxlwork.fragmet.RecommendFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

public class MainActivity2 extends AppCompatActivity {

    //声明tab和viewpage2标签
    private TabLayout tabl;
    private ViewPager2 vp2;
    //声明子页面数据源，使用fragment集合存储
    private List<Fragment> fragments;
    //声明子页面适配器
    private PageAdapter pageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);


        //获取控件对象
        getViews();
        //初始化子页面数据源
        initPages();

        //初始化子页面适配器对象
        pageAdapter = new PageAdapter(fragments,this);
        //设置选型卡切换时的滑动方向
        vp2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        //给viewPage2绑定适配器
        vp2.setAdapter(pageAdapter);
        //关联vp2和tablayout
        TabLayoutMediator mediator = new TabLayoutMediator(
                tabl,
                vp2,
                new TabLayoutMediator.TabConfigurationStrategy() {
                    @Override
                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                        //设置选项卡文本
                        switch (position){
                            case 0:
                                tab.setText("推荐");
                                break;
                            case 1:
                                tab.setText("个人中心");
                                break;
                        }
                    }
                }
        );
        //使tablayout和viewpage2连接
        mediator.attach();






    }
    //初始化子页面数据源
    private void initPages() {
        fragments = new ArrayList<>();
        fragments.add(new RecommendFragment());
        fragments.add(new MineFragment());


    }

    //获取控件对象
    private void getViews() {
        tabl = findViewById(R.id.tabl);
        vp2 = findViewById(R.id.vp2);

    }

}